//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
Page({
  data: {
    // color: "#0fb6ff",
    items: [],
    //开始坐标
    startX: 0,
    startY: 0,
    //全选
    all_select: true,
    //总数量
    cart_count: 0,
    //总金额
    total_price: 0.00,
    // 邮费
    total_yf: 0.00,
    // 订单信息字符串
    orderStr: "",
    // 购物车id
    cartId: 0,
    // 
    uid: "",
    // 填写价格-弹框
    peisongyoufei: '',
    hiddensubmit: true,
    nocancel: false,
    // 选择发货方式
    show: false,
    buttons: [
      {
        type: 'default',
        text: '客户自提',
        value: 0
      },
      {
        type: 'primary',
        text: '买家邮寄',
        value: 1
      }
    ],
  },
  onLoad: function () {
    this.setData({
      uid: wx.getStorageSync('uid'),
    })
    this.GetMyShopCart();
    // new app.WeToast();
    //未绑定跳转到绑定 暂时注释
    // if (app.globalData.binding == 0 || app.globalData.token ==''){
    //     wx.redirectTo({
    //       url: '../binding/binding',
    //     })
    // }
    //暂时注释
    // this.get_cart();
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //当前组索引
    var curBindex = e.currentTarget.dataset.bindex;
    //当前商品索引
    var curIndex = e.currentTarget.dataset.index;
    var items = this.data.items;
    //遍历修改滑动状态
    for (var i = 0; i < items.length; i++) {
      for (var j = 0; j < items[i].GoodsData.length; j++) {
        if (items[i].GoodsData[j].isTouchMove) {
          items[i].GoodsData[j].isTouchMove = false;
        }
      }
    }
    //更新坐标与数据
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: items
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      //当前索引
      curIndex = e.currentTarget.dataset.index,
      //当前组索引
      curBindex = e.currentTarget.dataset.bindex,
      //开始
      startX = that.data.startX,
      startY = that.data.startY,
      //滑动变化坐标
      touchMoveX = e.changedTouches[0].clientX,
      touchMoveY = e.changedTouches[0].clientY,
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    var items = that.data.items;
    var len = items[curBindex].GoodsData.length;
    for (var i = 0; i < len; i++) {
      items[curBindex].GoodsData[i].isTouchMove = false;
      //滑动超过30度角return
      if (Math.abs(angle) > 30) return;
      if (i == curIndex) {
        if (touchMoveX > startX) {
          //右滑
          items[curBindex].GoodsData[i].isTouchMove = false;
        } else {
          //左滑
          items[curBindex].GoodsData[i].isTouchMove = true
        }
      }
    }
    //更新数据
    that.setData({
      items: items
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //购物车——删除事件
  del: function (e) {
    var curBindex = e.currentTarget.dataset.bindex;
    var curIndex = e.currentTarget.dataset.index;
    var cartId = e.currentTarget.dataset.cartid;
    var items = this.data.items;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=DelShopCart&CarId=" + cartId),
      success: function (res) {
        console.log(JSON.parse(baseJs.decryUrl(res.data)));
        var json = JSON.parse(baseJs.decryUrl(res.data));
        if (json.ResultFlag == 1) {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        } else {
          wx.showToast({
            title: json.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
    items[curBindex].GoodsData.splice(curIndex, 1);
    this.setData({
      items: items
    });
    this.clear_item();

  },
  /* 点击减号 */
  bindMinus: function (e) {
    var items = this.data.items,
      curBindex = e.currentTarget.dataset.bindex,
      curIndex = e.currentTarget.dataset.index;
    // 如果大于1时，才可以减
    if (items[curBindex].GoodsData[curIndex].BuyNum > 1) {
      items[curBindex].GoodsData[curIndex].BuyNum--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = items[curBindex].GoodsData[curIndex].BuyNum <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.setData({
      items: items,
    });
    this.re_count(); //重新计算
  },
  // 点击加号
  bindPlus: function (e) {
    console.log(e);
    var items = this.data.items,

      curBindex = e.currentTarget.dataset.bindex,
      curIndex = e.currentTarget.dataset.index;
    var stockNum = e.currentTarget.dataset.value.stockNum - 0
    console.log(items);
    console.log(curBindex);
    console.log(curIndex);
    console.log(stockNum);
    // 不作过多考虑自增1
    if (items[curBindex].GoodsData[curIndex].BuyNum >= stockNum) {
      wx.showToast({
        icon: "error",
        title: '库存不足',
      })
      return
    }
    items[curBindex].GoodsData[curIndex].BuyNum++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = items[curBindex].GoodsData[curIndex].BuyNum < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.setData({
      items: items,
    });
    this.re_count(); //重新计算
  },
  /* 输入框事件 */
  bindManual: function (e) {
    var items = this.data.items,
      curBindex = e.currentTarget.dataset.bindex,
      curIndex = e.currentTarget.dataset.index;
    var num = e.detail.value;
    var stockNum = e.currentTarget.dataset.value.stockNum - 0
    if (isNaN(num)) {
      num = 1;
    }
    if (num > stockNum) { //判断库存
      wx.showToast({
        icon: "error",
        title: '库存不足',
      })
      this.setData({
        items: items,
      });
      return
    }
    items[curBindex].GoodsData[curIndex].BuyNum = num;
    // 将数值与状态写回
    this.setData({
      items: items,
    });
    this.re_count(); //重新计算
  },

  //把该组整体取消选中
  b_select: function (e) {
    var curBindex = e.currentTarget.dataset.bindex;
    var items = this.data.items;
    var len = items[curBindex].GoodsData.length;
    var selectStatus = items[curBindex].isSelect;
    for (var i = 0; i < items.length; i++) {
      if (i == curBindex) {
        if (selectStatus === false) {
          items[curBindex].isSelect = true;
        } else {
          items[curBindex].isSelect = false;
        }
        // } else {
        //   items[i].isSelect = false;
        //   for (var j = 0; j < items[i].GoodsData.length; j++) {
        //     items[i].GoodsData[j].isSelect = false;
        //   }
      }
    }
    // if (selectStatus === false) {
    //   items[curBindex].isSelect = true;
    // } else {
    //   items[curBindex].isSelect = false;
    // }
    for (var i = 0; i < len; i++) {
      if (selectStatus === false) {
        items[curBindex].GoodsData[i].isSelect = true;
      } else {
        items[curBindex].GoodsData[i].isSelect = false;
      }
    }
    //全选按钮
    var all_select;
    var ilen = items.length; //店数
    var num = 0;
    for (var j = 0; j < ilen; j++) {
      if (items[j].isSelect === true) {
        num++;
      }
    }
    if (num == ilen) {
      all_select = true;
    } else {
      all_select = false;
    }
    this.setData({
      all_select: all_select,
      items: items
    });
    //重新计算
    this.re_count();
  },
  //单选
  single_select: function (e) {
    var items = this.data.items;
    var curBindex = e.currentTarget.dataset.bindex;
    var curIndex = e.currentTarget.dataset.index;
    for (var i = 0; i < items.length; i++) {
      if (i == curBindex) {
        if (items[curBindex].GoodsData[curIndex].isSelect) {
          items[curBindex].GoodsData[curIndex].isSelect = false;
        } else {
          items[curBindex].GoodsData[curIndex].isSelect = true;
        }
        // } else {
        //   items[i].isSelect = false;
        //   for (var j = 0; j < items[i].GoodsData.length; j++) {
        //     items[i].GoodsData[j].isSelect = false;
        //   }
      }
    }
    //改变当前按钮
    // if (items[curBindex].GoodsData[curIndex].isSelect) {
    //   items[curBindex].GoodsData[curIndex].isSelect = false;
    // } else {
    //   items[curBindex].GoodsData[curIndex].isSelect = true;
    // }
    // console.log(items[curBindex]);
    //先改变当前组的状态
    var ilen = items.length;
    var len = items[curBindex].GoodsData.length;
    var inum = 0,
      num = 0,
      all_select;
    for (var j = 0; j < len; j++) {
      if (items[curBindex].GoodsData[j].isSelect === true) {
        num++;
      }
    }
    if (num == len) {
      items[curBindex].isSelect = true;
    } else {
      items[curBindex].isSelect = false;
    }
    //改变全选状态
    for (var i = 0; i < ilen; i++) {
      if (items[i].isSelect === true) {
        inum++;
      }
    }
    if (inum == ilen) {
      all_select = true;
    } else {
      all_select = false;
    }
    this.setData({
      items: items,
      all_select: all_select,
    });
    //重新计算
    this.re_count();
  },
  //全选
  all_select: function () {
    var all_select = this.data.all_select;
    var items = this.data.items;
    if (all_select === false) {
      //全选
      for (var i = 0; i < items.length; i++) {
        items[i].isSelect = true;
        for (var j = 0; j < items[i].GoodsData.length; j++) {
          items[i].GoodsData[j].isSelect = true;
        }
      }
      all_select = true;
    } else {
      //取消全选
      for (var i = 0; i < items.length; i++) {
        items[i].isSelect = false;
        for (var j = 0; j < items[i].GoodsData.length; j++) {
          items[i].GoodsData[j].isSelect = false;
        }
      }
      all_select = false;
    }
    this.setData({
      items: items,
      all_select: all_select
    });
    //重新计算
    this.re_count();
  },
  get_cart: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    wx.request({
      url: app.globalData.host + '/index.php/app/cart/get_cart_list',
      data: {
        token: app.globalData.token
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        if (res.data.code === 2000) {
          console.log(res);
          that.setData({
            items: res.data.data.cart_list,
            total_price: res.data.data.total_price,
            cart_count: res.data.data.cart_count
          });
        } else if (res.data.code == 8003) {
          that.relogin();
        } else {
          that.wetoast.toast({
            title: res.data.msg,
            duration: 1000
          });
        }
        wx.hideLoading();
      },
      fail: function () {
        that.wetoast.toast({
          title: '网络错误',
          duration: 1000
        });
      }
    })
  },
  //
  clear_item: function () {
    var items = this.data.items;
    for (var i = 0; i < items.length; i++) {
      if (items[i].GoodsData.length == 0) {
        items.splice(i, 1);
      }
    }
    this.setData({
      items: items
    });
    this.re_count();
  },
  //重新计算
  re_count: function () {
    var items = this.data.items,
      total_price = 0.00,
      cart_count = 0,
      total_yf = 0.00,
      // 选中的个数
      checkedCount = 0;
    var orderStr = this.data.orderStr;
    var cartId = this.data.cartId;

    for (var i = 0; i < items.length; i++) {
      for (var j = 0; j < items[i].GoodsData.length; j++) {
        if (items[i].GoodsData[j].isSelect === true) {
          cartId = i;
          checkedCount++;
          cart_count += parseInt(items[i].GoodsData[j].BuyNum);
          total_price += parseInt(items[i].GoodsData[j].BuyNum) * parseFloat(items[i].GoodsData[j].Price).toFixed(2);
          total_yf = parseFloat(items[i].GoodsData[j].YouFei).toFixed(2) * 1;
          if (checkedCount == 1) {
            orderStr += items[i].SJID + "+" + items[i].GoodsData[j].GoodsID + "*" + items[i].GoodsData[j].BuyNum + "*" + items[i].GoodsData[j].Model + "*" + parseFloat(items[i].GoodsData[j].Price).toFixed(2) + "*" + items[i].GoodsData[j].DeliverType;
          } else {
            orderStr += "|" + items[i].SJID + "*" + items[i].GoodsData[j].BuyNum + "*" + items[i].GoodsData[j].Model + "*" + parseFloat(items[i].GoodsData[j].Price).toFixed(2) + "*" + items[i].GoodsData[j].DeliverType;
          }
        }

      }

    }
    this.setData({
      total_price: parseFloat(total_price).toFixed(2),
      cart_count: cart_count,
      total_yf: parseFloat(total_yf).toFixed(2),
      orderStr: orderStr,
      cartId: cartId
    });
  },

  // 获取购物车
  GetMyShopCart: function () {

    var that = this;
    var uid = this.data.uid;
    var items = this.data.items;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=GetMyShopCart&UID=" + uid),
      success: function (res) {
        items = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        that.endOrderData(items);
        that.setData({
          items: items
        })
        console.log(items);
        wx.stopPullDownRefresh()
      }
    })
  },
  // 最外层循环
  endOrderData: function (arr) {
    var endArr = [];
    for (var i = 0; i < arr.length; i++) {
      arr[i].isSelect = false;
      for (var j = 0; j < arr[i].GoodsData.length; j++) {
        arr[i].GoodsData[j].isSelect = false;
        arr[i].GoodsData[j].isTouchMove = false;
      }
    }
    return endArr;
  },


  // 去结算
  goPay: function () {
    this.setData({
      show: true
    })
  },

  onPullDownRefresh: function () {
    this.GetMyShopCart()
  },

  // 客户选择邮寄或者自提
  buttontap(e) {
    var type = e.detail.index
    if (type == 0) {
      console.log("自提");
      this.sendOrder(1)
    } else {
      console.log("邮寄");
      this.sendOrder(0)
    }
  },


  // 确认发货方式发送给后台发送订单
  sendOrder(type) {
    var uid = wx.getStorageSync('uid');
    var buyGoods = '';
    var items = this.data.items;
    var loadList = [];
    for (var i = 0; i < items.length; i++) {
      for (var j = 0; j < items[i].GoodsData.length; j++) {
        if (items[i].GoodsData[j].isSelect) {
          loadList.push(items[i].GoodsData[j])
        } else {
        }
      }
    }
    for (var k = 0; k < loadList.length; k++) {
      if (buyGoods.length < 1) {
        buyGoods = loadList[k].GoodsID + "-" + loadList[k].BuyNum + "-" + loadList[k].Model;
      } else {
        buyGoods = buyGoods + "~" + loadList[k].GoodsID + "-" + loadList[k].BuyNum + "-" + loadList[k].Model;
      }
    }
    wx.request({
      url: baseJs.api_Order + "SettlementOrder",
      method: 'post',
      data: baseJs.json2Form({
        UID: uid,
        BuyGoodsInfo: buyGoods,
        PeiSongYouFei: '0',
        IsShouYinJiOrder: '0',
        IsZiTi: type,
        Remark: '',
      }),
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        var json = res.data.ResultData;
        // console.log(json);
        if (res.data.ResultFlag == 1) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
          this.setData({
            show: false
          })
          setTimeout(function () {
            wx.navigateTo({
              url: '/packageA/Orderpayment/Orderpayment?orderid=' + json.OrderId,
            })
          }, 1000)
        }
        if (res.data.ResultFlag == 0) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  }
})